import { InboxOutlined, PlusOutlined, RedoOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Upload,
  UploadFile,
  UploadProps,
} from 'antd';
import { sortTran, filterTranNew } from '@/utils/requestUtil';
import React, { useRef, useState } from 'react';
import {
  addMaterialInfo,
  delMaterialInfo,
  exportMaterialInfo,
  getMaterialInfoByPage,
  materialBasicInfoSync,
  updateMaterialInfo,
  uploadMaterialInfo,
} from '@/services/baseData/materialInfo';
import { Ellipsis } from '@/components/Ellipsis';

const MaterialInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建或编辑提示框
  const [modalVisit2, setModalVisit2] = useState(false); //导入提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //提示框加载加载
  const [formTitle, setFormTitle] = useState('新建'); //提示框标题
  const [form] = Form.useForm();
  const { Dragger } = Upload; //附件的拖拽上传
  const [file, setFile] = useState<UploadFile[]>(); //导入的文件
  const fileTypeList = ['xlsx', 'xls']; //设定的允许上传文件数组
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '规格型号',
      dataIndex: 'materialSpec',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '参数',
      dataIndex: 'para',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '物料分类',
      dataIndex: 'category',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '是否有效',
      dataIndex: 'effective',
      align: 'center',
      sorter: true,
      valueType: 'select',
      fieldProps: {
        options: [
          { value: 1, label: '是' },
          { value: 0, label: '否' },
        ],
      },
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '属性名称',
      dataIndex: 'materialProperty',
      align: 'center',
      sorter: true,
      valueType: 'select',
      fieldProps: {
        options: [
          { value: '生产加工', label: '生产加工' },
          { value: '产成品', label: '产成品' },
        ],
      },
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              ...record,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const result = await delMaterialInfo(record);
                if (result && result.code === 0) {
                  message.success('删除成功');
                } else message.error('删除失败');
                actionRef.current?.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  //新增或编辑确定
  const handleSubmit = async () => {
    setConfirmLoading(true);

    if (formTitle === '新建') {
      const res = form.getFieldsValue();
      const result = await addMaterialInfo(res);
      //如果添加成功
      if (result && result.code === 0) {
        message.success('新建成功');
      } else message.error('新建失败');
    } else if (formTitle === '编辑') {
      const res = form.getFieldsValue();
      const result = await updateMaterialInfo(res);
      //如果更新成功
      if (result && result.code === 0) {
        message.success('更新成功');
      } else message.error('更新失败');
    }

    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current?.reload();
  };

  //下载模板
  const handleDownload = () => {
    const res = {
      current: 0,
      filters: [],
      pageSize: 0, //API特殊要求
      sorters: [],
    };
    exportMaterialInfo(res).then((result) => {
      const aLink = document.createElement('a');
      document.body.appendChild(aLink);
      aLink.style.display = 'none';
      aLink.href = window.URL.createObjectURL(result);
      aLink.setAttribute('download', `materialTemplate.xls`);
      aLink.click();
      document.body.removeChild(aLink);
    });
  };

  //将upload组件的文件保存在file中
  const onFilesChange: UploadProps['onChange'] = (info: any) => {
    let newFile = [...info.fileList];
    newFile = newFile.splice(-1); //限制上传个数
    const fileType = info.file.name.split('.').pop();
    if (fileTypeList.indexOf(fileType) != -1) {
      setFile(newFile);
    }
    /*     if(fileType === 'xlsx' || fileType === 'xls'){
      setFile(newFile);
    } */
  };

  //选择文件后检验
  const beforeUpload = (file: any) => {
    const fileType = file.name.split('.').pop();
    if (fileTypeList.indexOf(fileType) === -1) {
      message.error('上传失败：上传文件格式不正确');
    }
    /*     if (fileType !== 'xlsx' && fileType !== 'xls') {
      message.error(`上传失败：上传文件格式不正确`);
    } */
    return false;
  };

  //导入物料主数据
  const handleUpload = async () => {
    const formData = new FormData();
    //如果没有选择文件
    if (file === void 0) {
      message.error('请选择文件');
      return;
    }
    formData.append('file', file[0].originFileObj);
    const result = await uploadMaterialInfo({ file: formData });
    if (result && result.code === 0) {
      message.success('导入成功');
    } else message.error('导入失败');
    actionRef.current?.reload();
    setFile([]); //清空文件
    setModalVisit2(false);
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="物料数据查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        search={{ span: 4, labelWidth: 80 }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<RedoOutlined />}
            type="primary"
            onClick={async () => await materialBasicInfoSync()}
          >
            主数据同步
        </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button key="button" type="primary" onClick={() => setModalVisit2(true)}>
            导入
          </Button>,
          <Button key="button" type="primary" onClick={handleDownload}>
            下载模板
          </Button>,
        ]}
        request={async (params = {}, sort) => {
          const sorters = sortTran(sort);
          const filters = filterTranNew(params);
          const result = await getMaterialInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          console.log(result, 'res');
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        pagination={{
          pageSize: 100,
          pageSizeOptions: [100, 500, 1000],
        }}
        scroll={{ y: 500 }}
        columns={columns}
        rowSelection={{}}
      />

      {/* 新建与编辑窗口 */}
      <Modal
        title={formTitle}
        visible={modalVisit}
        width={1000}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '95px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
        >
          <Form.Item name="id" label="id" hidden={true}>
            <Input />
          </Form.Item>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="materialCode"
                label="物料编号"
                rules={[{ required: true, message: '请输入物料名称!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="materialName"
                label="物料名称"
                rules={[{ required: true, message: '请输入物料名称!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="para"
                label="参数"
                rules={[{ required: true, message: '请输入参数!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="物料分类"
                rules={[{ required: true, message: '请输入物料分类!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="barCode"
                label="条码"
                rules={[{ required: true, message: '请输入条码!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="brand"
                label="品牌"
                rules={[{ required: true, message: '请输入品牌!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="unit"
                label="单位"
                rules={[{ required: true, message: '请输入单位' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="materialSpec"
                label="规格型号"
                rules={[{ required: true, message: '请输入规格型号!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="effective"
                label="是否有效"
                rules={[{ required: true, message: '请选择是否有效!' }]}
              >
                <Select
                  placeholder="请选择是否有效"
                  onChange={() => { }}
                  options={[
                    { value: 1, label: '是' },
                    { value: 0, label: '否' },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="materialProperty"
                label="属性名称"
                rules={[{ required: true, message: '请输入属性名称!' }]}
              >
                <Select
                  placeholder="请选择属性名称"
                  onChange={() => { }}
                  options={[
                    { value: '生产加工', label: '生产加工' },
                    { value: '产成品', label: '产成品' },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 导入窗口 */}
      <Modal
        title="导入"
        visible={modalVisit2}
        confirmLoading={confirmLoading}
        onOk={handleUpload}
        onCancel={() => {
          setModalVisit2(false);
          setFile([]); //清空文件
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传工时周期文件!' }]}
          >
            <Upload
              accept={'.xlsx,.xls'}
              listType="picture"
              fileList={file}
              onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
        {/*         <Dragger
          accept={'.xlsx,.xls'}
          listType="picture"
          fileList={file}
          onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
          multiple={false}
          beforeUpload={beforeUpload}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击上传</p>
        </Dragger> */}
      </Modal>
    </PageHeaderWrapper>
  );
};
export default MaterialInfo;
